package com.gitee.qdbp.general.system.web.views;

import java.util.Locale;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.ContextLoader;
import com.gitee.qdbp.able.beans.DepthMap;
import com.gitee.qdbp.base.utils.WebTools;
import eu.bitwalker.useragentutils.DeviceType;
import eu.bitwalker.useragentutils.OperatingSystem;

/**
 * 页面跳转基础处理
 *
 * @author zhaohuihua
 * @version 170427
 */
public class SimpleViewsTools {

    private DepthMap pageVariables;
    private boolean autoSetLocale;

    public SimpleViewsTools(Properties setting) {
        this.pageVariables = DepthMap.load(setting, "pv");
        this.autoSetLocale = setting.contains("pv.locale");
    }

    public DepthMap getPageVariables() {
        DepthMap dmp = pageVariables.copy();
        if (autoSetLocale) {
            try {
                dmp.put("locale", getLocaleType());
            } catch (NoSuchMessageException ignore) {
            }
        }
        return dmp;
    }

    public String getLocaleType() {
        Locale locale = LocaleContextHolder.getLocale();
        MessageSource context = ContextLoader.getCurrentWebApplicationContext();
        return context.getMessage("i18n.global.locale.type", null, locale);
    }

    public String getDeviceType() {
        return isMobileDeviceType() ? "h5" : "pc";
    }

    public boolean isMobileDeviceType() {
        HttpServletRequest request = WebTools.me.getRequest();
        String userAgent = request.getHeader("User-Agent");
        DeviceType device = DeviceType.MOBILE;
        if (userAgent != null) {
            String userAgentLowercaseString = userAgent.toLowerCase();
            OperatingSystem operatingSystem = OperatingSystem.parseUserAgentLowercaseString(userAgentLowercaseString);
            device = operatingSystem.getDeviceType();
        }
        return device != DeviceType.COMPUTER;
    }
}
